package odometerDevice.connectionDevice.android.bluetooth;

import java.io.IOException;

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

public class RequestConnection {

    public StreamConnection getConnection() {
	// retrieve the local Bluetooth device object
	LocalDevice local = null;

	StreamConnectionNotifier notifier = null;
	StreamConnection connection = null;

	// setup the server to listen for connection
	try {
	    local = LocalDevice.getLocalDevice();
	    local.setDiscoverable(DiscoveryAgent.GIAC);

	    UUID uuid = new UUID("9E3BB2F187B14C5682C6339CBF929BBB", false);
	    System.out.println(uuid.toString());

	    String url = "btspp://localhost:" + uuid.toString()
		    + ";name=RemoteBluetooth";
	    notifier = (StreamConnectionNotifier) Connector.open(url);
	} catch (BluetoothStateException e) {
	    System.out.println("Bluetooth is not turned on.");
	    e.printStackTrace();
	    return null;
	} catch (IOException e) {
	    e.printStackTrace();
	    return null;
	}

	try {
	    System.out.println("waiting for Android connection...");
	    connection = notifier.acceptAndOpen();

	    return connection;
	} catch (Exception e) {
	    e.printStackTrace();
	    return null;
	}
    }

}
